package pp

import (
	"os"
	"path"

	"github.com/BurntSushi/toml"
	"github.com/mitchellh/go-homedir"
)

// Config 配置.
type Config struct {
	// Width 窗口宽度.
	Width int `toml:"-"`
	// Height 窗口高度.
	Height int `toml:"-"`
	// UDPPort UDP端口.
	UDPPort  int `toml:"-"`
	BuffSize int `toml:"-"`
	// RPCPort 远程访问端口.
	RPCPort int `toml:"-"`
	// UserID 用户ID.
	UserID string `toml:"-"`
	// 本人昵称.
	Nick string
}

// NewConfig 新建配置.
func NewConfig() *Config {
	c := &Config{}

	if home, err := homedir.Dir(); err == nil {
		_, _ = toml.DecodeFile(path.Join(home, ".pp.toml"), c)
	}

	if c.UDPPort == 0 {
		c.UDPPort = 9091
	}

	if c.RPCPort == 0 {
		c.RPCPort = 9090
	}

	return c
}

// Save 保存配置.
// nolint: wrapcheck
func (c *Config) Save() error {
	home, err := homedir.Dir()
	if err != nil {
		return err
	}

	file, err := os.Create(path.Join(home, ".pp.toml"))
	if err != nil {
		return err
	}

	defer file.Close()

	encode := toml.NewEncoder(file)

	return encode.Encode(c)
}
